package com.seeyon.ctp.rest.resources;

import com.seeyon.apps.quartz.IQuartzTask;
import com.seeyon.apps.quartz.abstra.AbstractQuartzTask;
import com.seeyon.apps.quartz.form.QuartzFormFieldEnum;
import com.seeyon.apps.quartz.util.CAP4FormKit;
import com.seeyon.apps.quartz.util.CronTransUtil;
import com.seeyon.apps.quartz.util.QsQuartzUtil;
import com.seeyon.cap4.form.api.FormApi4Cap4;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.annotation.RestInterfaceAnnotation;
import org.apache.commons.logging.Log;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fgw
 * 定时任务路径
 */
@Path("quartzManager")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class QuartzTaskResource extends BaseResource {
	
    private static final Log LOG = CtpLogFactory.getLog(QuartzTaskResource.class);
	private FormApi4Cap4 formApi4Cap4;
	private FormBean form;


	/**
	 * 停止定时任务
	 * @param param
	 * @return
	 */
    @POST
    @Path("stop")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response stop(Map<String, String> param) {
    	FormDataMasterBean master;
		try {
			master = getMaster(param);
		} catch (Exception e) {
			LOG.error("获取表单数据失败：", e);
			return fail("获取表单失败！");
		}
		String jobBeanName = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.jobBeanName.getDisplay());
		try {
			QsQuartzUtil.deleteJob(jobBeanName);
		} catch (Exception e) {
			return fail("删除任务失败：" + e.getMessage());
		}
		// 更新状态
		CAP4FormKit.setCellValue(master, QuartzFormFieldEnum.state.getDisplay(), AppContext.currentUserName() + "停止了任务");
		CAP4FormKit.setCellValue(master, QuartzFormFieldEnum.isRunning.getDisplay(), "0");
		// 保存数据
		try {
			formApi4Cap4.saveOrUpdateFormData(master, form.getId(), true);
		} catch (Exception e) {
			LOG.error("任务停止成功，但是更新表单状态失败：", e);
			return fail("任务停止成功，但是更新表单状态失败");
		} 
        return success("任务已经停止：" + jobBeanName);
    }
    
    /**
     * 执行一次任务
     * @param param
     * @return
     */
    @POST
    @Path("exec")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response exec(Map<String, String> param) {
    	FormDataMasterBean master;
		try {
			master = getMaster(param);
		} catch (Exception e) {
			LOG.error("获取表单数据失败：", e);
			return fail("获取表单失败！");
		}
		String jobBeanId = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.jobBeanId.getDisplay());
		String jobBeanName = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.jobBeanName.getDisplay());
		AbstractQuartzTask task = (AbstractQuartzTask) AppContext.getBean(jobBeanId);
		if(null == task) {
			return fail(jobBeanId + "未在spring中进行定义，请联系开发人员！");
		}
		String taskParam = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.param.getDisplay());
		Map<String, String> params = new HashMap<String, String>();
		params.put(IQuartzTask.JOB_NAME, jobBeanName);
		params.put(IQuartzTask.JOB_PARAM, taskParam);
		String res = task.executeFunc(params);
        return success("任务执行完成:" + res);
    }
    
    @POST
    @Path("start")
    @RestInterfaceAnnotation(OpenExternal = RestInterfaceAnnotation.External.NO, StartVersion = "V7.0")
    public Response start(Map<String, String> param) {
    	FormDataMasterBean master;
		try {
			master = getMaster(param);
		} catch (Exception e) {
			LOG.error("获取表单数据失败：", e);
			return fail("获取表单失败！");
		}
		String cron = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.cron.getDisplay()); 
		try {
			CronTransUtil.validateCron(cron);
		} catch (ParseException e) {
			return fail("cron表达式有误:" + e.getMessage());
		}
		String jobBeanId = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.jobBeanId.getDisplay());
		AbstractQuartzTask task;
		try {
			task = (AbstractQuartzTask) AppContext.getBean(jobBeanId);
			if(null == task) {
				return fail(jobBeanId + "未在spring中进行定义，请联系开发人员！");
			}
		} catch(Exception e) {
			return fail("获取任务bean失败:" + e.getMessage());
		}
		String jobBeanName = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.jobBeanName.getDisplay());
		Date start = (Date) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.start.getDisplay());
		Date end = (Date) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.end.getDisplay());
		String taskParam = (String) CAP4FormKit.getFieldValue(master, QuartzFormFieldEnum.param.getDisplay());
		// 校验字段
		String validateStr = task.validateParam(taskParam);
		if(null != validateStr && !"".equals(validateStr)) {
			return fail(validateStr);
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put(IQuartzTask.JOB_NAME, jobBeanName);
		params.put(IQuartzTask.JOB_PARAM, taskParam);
		try {
			boolean startFlag = QsQuartzUtil.registerSyncTask(jobBeanId, jobBeanName, cron, start, end, params);
			if(!startFlag) {
				return fail("定时任务注册失败！");
			}
		} catch (Exception e) {
			LOG.error("定时任务注册失败：", e);
			return fail("定时任务注册失败:" + e.getMessage());
		}
		// 更新状态
		CAP4FormKit.setCellValue(master, QuartzFormFieldEnum.state.getDisplay(), AppContext.currentUserName() + "启动了任务");
		CAP4FormKit.setCellValue(master, QuartzFormFieldEnum.isRunning.getDisplay(), "1");
		// 保存数据
		try {
			formApi4Cap4.saveOrUpdateFormData(master, form.getId(), true);
		} catch (Exception e) {
			LOG.error("任务启动成功，但是更新表单状态失败：", e);
			return fail("任务启动成功，但是更新表单状态失败");
		} 
        return success(jobBeanName + "定时任务注册成功！");
    }
    
    private void getForm(Long formId) {
    	if(null == form) {
    		form = getFormApi4Cap4().getForm(formId, false);
    	}
    }
    
    private FormDataMasterBean getMaster(Map<String, String> param) throws Exception {
    	Long id = Long.valueOf(param.get("masterId"));
		Long formId = Long.valueOf(param.get("formId"));
		getForm(formId);
		// 获取表单数据
		FormDataMasterBean master = formApi4Cap4.getDataMasterBeanById(id, form, null);
		return master;
    }

    private FormApi4Cap4 getFormApi4Cap4() {
    	if(null == formApi4Cap4) {
    		formApi4Cap4 = (FormApi4Cap4) AppContext.getBean("formApi4Cap4");
    	}
		return formApi4Cap4;
	}    
}
